(function() {
    'use strict';

    angular.module("weApp.services", [])

            .factory('requestInerceptor', ['$q', function($q) {
                    var interceptor = {
                        'request': function(config) {

                            if (config.method == "POST") {

                                // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
                                config.headers['regionCode'] = '440700';
                                config.headers['manufacturer'] = 'sxyd';
                                config.headers['versionCode'] = '17';
                                config.headers['deviceId'] = 'wx' + Date.parse(new Date());
                                config.headers['osType'] = '3';
                                config.headers['bi_auth'] = 'bus_intelligence';
                                // config.headers = {
                                // 	'content-type' : "application/x-www-form-urlencoded"
                                // 	// ,'regionCode' : '610600'
                                // 	// ,'manufacturer' : 'sxyd'
                                // 	// 'deviceId' : "wexin01234567890",
                                // 	// 'osType' : "3",
                                // 	// 'bi_auth' : "bus_intelligence"
                                // }
                                // console.log( config )
                            }

                            return config || $q.when(config);
                        },
                        'requestError': function(rejection) {
                            return $q.reject(rejection);
                        },
                        'response': function(response) {
                            return response || $q.when(response);
                        },
                        'responseError': function(rejection) {
                            // console.log( rejection );
                            return $q.reject(rejection);
                        }


                    };
                    return interceptor;
                }])

            .factory('checkUserPosition', ['$rootScope', function($rootScope) {
                    var service = {
                        getDistance: getDistance
                    };

                    //经纬度转换成三角函数中度分表形式
                    var Rad = function(d) {
                        return d * Math.PI / 180.0;
                    };

                    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
                    function getDistance(lat1, lng1, lat2, lng2) {
                        var radLat1 = Rad(lat1);
                        var radLat2 = Rad(lat2);
                        var a = radLat1 - radLat2;
                        var b = Rad(lng1) - Rad(lng2);
                        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
                        s = s * 6378.137;// EARTH_RADIUS;
                        s = Math.round(s * 10000) / 10000; //输出为公里
                        //s=s.toFixed(4);
                        return s;
                    }

                    return service;

                }])

            .factory('weAppDataBase', ['$rootScope', '$q', function($rootScope, $q) {
                    var service = {
                        createDB: createDB,
                        insert: insertDB,
                        update: updateDB,
                        query: queryDB,
                        deleteDB: deleteDB,
                        dropDB: dropDB,
                        cleanDB: cleanDB
                    };

                    var webSQLInfo = {
                        dbName: 'weAppDB',
                        dbVersion: '1.0',
                        dbDisplayName: 'weApp StationLine DataBase',
                        dbEstimatedSize: 1 * 1024 * 1024
                    };

                    var weAppDB = null;

                    /**
                     * 创建数据库
                     * @return {[type]} [description]
                     */
                    function createDB() {
                        weAppDB = window.openDatabase(webSQLInfo.dbName, webSQLInfo.dbVersion, webSQLInfo.dbDisplayName, webSQLInfo.dbEstimatedSize);
                        weAppDB.transaction(function(tx) {
                            tx.executeSql("CREATE TABLE IF NOT EXISTS weAppDB ( lineId TEXT PRIMARY KEY, lineName TEXT, cityMapCode INTEGER, cityName TEXT) ", [],
                                    function(tx, result) {
                                        // console.log("weAppDB created successful.");
                                    },
                                    function(tx, error) {

                                        console.log("weAppDB created error." + error.message);
                                    })
                        })
                    }
                    ;

                    /**
                     * 插入数据
                     * @param  {[type]} lineId      [description]
                     * @param  {[type]} lineName    [description]
                     * @param  {[type]} cityMapCode [description]
                     * @param  {[type]} cityName    [description]
                     * @return {[type]}             [description]
                     */
                    function insertDB(lineId, lineName, cityMapCode, cityName) {
                        weAppDB.transaction(function(tx) {
                            tx.executeSql("INSERT INTO weAppDB ( lineId, lineName, cityMapCode, cityName ) VALUES (?, ?, ?, ?)",
                                    [lineId, lineName, cityMapCode, cityName],
                                    function(tx, result) {
                                        // console.log("insert successful!");
                                    },
                                    function(tx, error) {
                                        // console.log("insert error." + error.message);
                                    })
                        })
                    }
                    ;

                    /**
                     * 更新数据
                     * @return {[type]} [description]
                     */
                    function updateDB() {

                    }
                    ;

                    /**
                     * 检索数据
                     * @param  {[type]} city     [description]
                     * @param  {[type]} lineName [description]
                     * @return {[type]}          [description]
                     */
                    function queryDB(city, lineName) {
                        var sql = "SELECT * FROM weAppDB WHERE cityMapCode = " + city + " AND lineName LIKE '%" + lineName + "%' ";
                        var deferred = $q.defer();
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql, [],
                                    function(tx, result) {
                                        deferred.resolve(result.rows);
                                    },
                                    function(tx, error) {
                                        console.warn(error.message);
                                        deferred.reject(error);
                                    })
                        });
                        return deferred.promise;
                    }
                    ;

                    function deleteDB() {
                        var sql = "DELETE FROM weAppDB";
                        var deferred = $q.defer();
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql, [],
                                    function(tx, result) {
                                        deferred.resolve(result);
                                    },
                                    function(tx, error) {
                                        // console.warn(error.message);
                                        deferred.reject(error);
                                    })
                        });
                        return deferred.promise;
                    }
                    ;

                    /**
                     * 删除数据库
                     * @return {[type]} [description]
                     */
                    function dropDB() {
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(" DROP TABLE weAppDB ");
                        })
                    }
                    ;

                    function cleanDB() {
                        var sql = "DELETE FROM weAppDB WHERE lineName in ( select lineName frome weAppDB group by lineName having count(lineName) > 1 ) and lineId not in ( select min(lineId) from weAppDB group by lineName having count(lineName) > 1 ) ";
                        weAppDB.transaction(function(tx) {
                            tx.executeSql(sql);
                        });
                    }


                    return service;

                }])

            /**
             * 全局跳转至某个线路详情页面的跳转服务
             */
            .factory('showLinePageService', ['$timeout', '$state', function($timeout, $state) {
                    var service = {
                        gotoLinePage: gotoLinePage
                    };

                    function gotoLinePage(line, event, params) {

                        if (window.sessionStorage) {

                            sessionStorage.setItem("nowLineName", line.lineName);
                            sessionStorage.setItem("clickLine", JSON.stringify(line));
                            $state.go('line', params);

                        } else {
                            console.warn("your browser is not support sessionStorage.");
                        }

                    }

                    return service;
                }])

            /**
             * 全局线路列表中，收藏按钮公用服务
             * 点击收藏后将会将当前线路的ID和线路的JSON数据存入sessionStorage中:
             * @ myFavors        [Array] 收藏ID数组
             * @ myFavorsJSON    [JSON] 收藏JSON数据
             */
            .factory('myFavorsService', ['$timeout', 'localStorageService', function($timeout, localStorageService) {
                    var service = {
                        set: setFavor,
                        getId: getFavorId,
                        getJson: getFavorJson,
                        remove: removeFavor,
                        removeAll: removeFavorAll
                    };

                    /**
                     * 新增一条收藏线路
                     * @param {[type]} line [description]
                     */
                    function setFavor(line) {

                        var tmp_favors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        tmp_favors.push(line.lineStationId);
                        localStorageService.set("myFavors", JSON.stringify(tmp_favors));

                        var tmp_favorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));

                        var tmp_stationObj = {
                            "stationId": line.stationId,
                            "stationName": line.stationName,
                            "lineStations": [line]
                        };

                        /**
                         * 如果循环所有已收藏线路都没有找到对应所在站点，则新建一个站点
                         * @type {Boolean}
                         */
                        var mustCreateNewStationObject = true;

                        for (var i = 0; i < tmp_favorsJSON.length; i++) {
                            if (tmp_favorsJSON[i].stationId == line.stationId) {
                                // console.log("have this stationID");
                                tmp_favorsJSON[i].lineStations.push(line);
                                mustCreateNewStationObject = !mustCreateNewStationObject;
                                break;
                            }
                        }

                        /**
                         * 如果循环所有已收藏线路都没有找到对应所在站点，则新建一个站点
                         * @type {Boolean}
                         */
                        if (mustCreateNewStationObject) {
                            // console.log("create a new stationID");
                            tmp_favorsJSON.push(tmp_stationObj);
                        }
                        ;

                        if (!tmp_favorsJSON.length)
                            tmp_favorsJSON.push(tmp_stationObj);

                        // tmp_favorsJSON.push( line );
                        localStorageService.set("myFavorsJSON", JSON.stringify(tmp_favorsJSON));

                        // console.log( tmp_favorsJSON );

                    }
                    ;

                    function getFavorId() {
                        return localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                    }
                    ;

                    function getFavorJson() {
                        return localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));
                    }
                    ;

                    /**
                     * 移除一条收藏线路
                     * @param  {[type]} line [description]
                     * @return {[type]}      [description]
                     */
                    function removeFavor(line) {

                        var lineId = line.lineStationId;

                        var tmp_favors = localStorageService.get("myFavors") == null ? [] : JSON.parse(localStorageService.get("myFavors"));
                        var tmp_favorsJSON = localStorageService.get("myFavorsJSON") == null ? [] : JSON.parse(localStorageService.get("myFavorsJSON"));

                        if (tmp_favors == tmp_favorsJSON == null)
                            return;

                        tmp_favors.remove(lineId);
                        localStorageService.set("myFavors", JSON.stringify(tmp_favors));

                        for (var i = 0; i < tmp_favorsJSON.length; i++) {
                            var thisStation = tmp_favorsJSON[i];
                            for (var j = 0; j < thisStation.lineStations.length; j++) {
                                // console.log( thisStation.lineStations[j].lineStationId );
                                if (thisStation.lineStations[j].lineStationId == lineId) {
                                    thisStation.lineStations.splice(j, 1);
                                    break;
                                }
                            }
                            if (!thisStation.lineStations.length)
                                tmp_favorsJSON.splice(i, 1);
                        }

                        localStorageService.set("myFavorsJSON", JSON.stringify(tmp_favorsJSON));

                    }
                    ;

                    /**
                     * 移除全部收藏线路
                     * @return {[type]} [description]
                     */
                    function removeFavorAll() {
                        localStorageService.remove("myFavors");
                        localStorageService.remove("myFavorsJSON");
                    }
                    ;

                    return service;

                }]);


})();